/**
 * Copyright (C), 2015-2021, 开度
 * FileName: MyInvocationSecurityMetadataSourceService
 * Author:   ASUS
 * Date:     2021/4/28 10:19
 * Description: 自定义的Metadata，通过当前请求地址，获取该地址所需要的角色
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2021/4/28           1.0              自定义的Metadata，通过当前请求地址，获取该地址所需要的角色
 */
package com.example.spring.security.interceptor.menu;

import com.example.spring.security.mapper.MenuRoleRelationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 〈自定义的Metadata，通过当前请求地址，获取该地址所需要的角色〉
 *
 * @author ASUS
 * @create 2021/4/28
 * @since 1.0.0
 */
@Slf4j
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuRoleRelationMapper menuRoleRelationMapper;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
        String uri = request.getRequestURI();
        // 查出资源所需要的角色
        List<String> roleNameList = menuRoleRelationMapper.selectRoleByMenuKey(uri);
        if(roleNameList!=null){
            List<ConfigAttribute> attributes = new ArrayList();
            for(String roleName:roleNameList){
                attributes.add(new SecurityConfig(roleName));
            }
            return attributes;
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
